var Twitterbook = {
    initialized: false,
    SQLite: '',
    
    start: function() {
        if (Twitterbook.initialized == false) {
	    Twitterbook.initialized = true;
            Twitterbook.loadUsers(document);
            Twitterbook.loadArchived(document);
	}
    },
    
    loadUsers: function(doc) {
        var users = Twitterbook.getAllLogins();
        var menu = doc.getElementById('twitbook_users');
        
        length = menu.itemCount;
        for(var i=length-1;i>=0;i--) {
            menu.removeItemAt(i);
        }
        
        for(i=0;i<users.length;i++) {
            if (Twitterbook.getPref('login') == users[i]) users[i] = '• '+users[i];
            item = menu.appendItem(users[i]);
            item.setAttribute('oncommand', 'changeUser(\''+users[i]+'\');');
        }
    },
    
    loadArchived: function(doc) {
        var archive = Twitterbook.getArchives();
        var menu = doc.getElementById('twitbook_archives');
        
        length = menu.itemCount;
        for(var i=length-1;i>=0;i--) {
            menu.removeItemAt(i);
        }
        
        for(i=0;i<archive.length;i++) {
            item = menu.appendItem(archive[i]);
        }
    },
    
    twitt: function() {
        var text = Twitterbook.getPref('message')+window._content.document.URL;
        Twitterbook.addTwit(text);
    },
    
    setPref: function(type, value) {
        var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref("extensions.twitterbook."+type, value);
    },
    
    setPass: function(login, password) {
        var myLoginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
        var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init");
        var myLoginInfo = new nsLoginInfo('chrome://twitterbook', 'Twitter Login', null, login, password, '', '');
        
        var oldLogin = Twitterbook.loginExist(login);
        if (oldLogin != false) {
            myLoginManager.modifyLogin(oldLogin, myLoginInfo);
        } else {
            myLoginManager.addLogin(myLoginInfo);
        }
    },
    
    getPref: function(type) {
        var prefs = Components.classes["@mozilla.org/preferences-service;1"].
                    getService(Components.interfaces.nsIPrefBranch);
                  
        try  {
            if (type == 'message') {
                return prefs.getCharPref("extensions.twitterbook.message");
            } else if (type == 'pass') {
                var login = Twitterbook.getPref('login');
                var pass = '';
                
                var passwordManager = Components.classes["@mozilla.org/login-manager;1"]
                         .getService(Components.interfaces.nsILoginManager);
 
                // Find users for this extension 
                var logins = passwordManager.findLogins({}, 'chrome://twitterbook', 'Twitter Login', null);
                       
                for (var i = 0; i < logins.length; i++) {
                    if (logins[i].username == login) {
                        pass = logins[i].password;
                        break;
                    }
                }
                return pass;
            } else {
                return prefs.getCharPref("extensions.twitterbook.login");
            }
        } catch(ex) {
            Twitterbook.setPref(type, '');
            return '';
        }
    },
    
    loginExist: function(login) {
        var exist = false;
        var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
 
        // Find users for this extension 
        var logins = passwordManager.findLogins({}, 'chrome://twitterbook', 'Twitter Login', null);
                       
        for (var i = 0; i < logins.length; i++) {
            if (logins[i].username == login) {
                exist = logins[i];
                break;
            }
        }
        return exist;
    },
    
    remove: function(login) {
        var myLoginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
        myLoginManager.removeLogin(login);
    },
    
    getAllLogins: function() {
        var passwordManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
        var log = new Array();
        
        // Find users for this extension 
        var logins = passwordManager.findLogins({}, 'chrome://twitterbook', 'Twitter Login', null);
                       
        for (var i = 0; i < logins.length; i++) {
            log[i] = logins[i].username;
        }
        return log;
    },
    
    
    addTwit: function(d) {
        var email = Twitterbook.getPref('login');
        var password = Twitterbook.getPref('pass');
        
        if (email == '' | password == '') {
            alert('You need to define your Twitter email and password');
        } else {
            var page = 'http://'+email+':'+password+'@twitter.com/statuses/update.xml';
            var data = 'source=twitterbook&status='+encodeURI(d);
            
            var XhrObj = new XMLHttpRequest();
            XhrObj.open("POST", page);
            
            //Ok pour la page cible
            XhrObj.onreadystatechange = function() {
                if (XhrObj.readyState == 4 && XhrObj.status == 200) {
                    if (Twitterbook.SQLite != '') {
                        Twitterbook.SQLite.sql('INSERT INTO twits (url) VALUES (\''+d+'\');');
                    }
                    Twitterbook.loadArchived(document);
                    
                    alert('Le twit a été ajouté');
                }
            }
            
            if (data == undefined) data = '';
            
            XhrObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            XhrObj.send(data);
        }
    },
    
    getArchives: function() {
        if (Twitterbook.SQLite == '') return false;
        
        var twits = Twitterbook.SQLite.query('SELECT * FROM twits');
        if (twits == false) return twits;
        
        var ret = new Array();
        var i = 0;
        while (twits.executeStep()) {
            ret[i] = twits.getString(0);
            i++;
        }
        
        return ret;
    }
}